//
// Created by hamlet on 2022/1/5.
//

#ifndef TIANQI_TIANQIACCESSER_H
#define TIANQI_TIANQIACCESSER_H

#include <QObject>
#include <QVariant>
#include "tianqidata.h"

QT_BEGIN_NAMESPACE
class QNetworkAccessManager;
class QNetworkReply;
class QSettings;
class QTimer;
QT_END_NAMESPACE

class TianqiAccesser : public QObject {
Q_OBJECT

public:
    explicit TianqiAccesser(QObject *parent = nullptr);
    ~TianqiAccesser() override;

    void readSettings();
    void writeSettings(TianqiMethod method, QVariant method_data);

    void restartCaching();  // 开始缓存期，缓存器为CACHE_TIMES个更新周期

    [[nodiscard]] TianqiMethod getMethod() const;
    [[nodiscard]] const QVariant &getMethodData() const;
    [[nodiscard]] const TianqiData &getData() const;

signals:
    void sign_needUpdate();  // 新的TianqiData已获取，需要刷新
    void sign_freeMemory();  // 缓存期已过，需要释放内存

public slots:
    void requestData();
    void requestDataAndCache();  // 获取并重新缓存（用于手动刷新情况）
    void processData(QNetworkReply *reply);

private:
    static constexpr int TIME_INTERVAL = 750;
    static constexpr int TIME_STEP = 600000;
    static constexpr unsigned CACHE_TIMES = 2;

    QSettings *m_settings;
    TianqiMethod m_method;
    QVariant m_methodData;
    TianqiData m_data;

    void setSettingsEnabled(bool state);

    QNetworkAccessManager *m_manager;
    QTimer *m_timer;
    int m_sentRequestTimes;
    unsigned m_settingsRemaining;

    void sendRequest(const QString &url);
};


#endif //TIANQI_TIANQIACCESSER_H
